<template>
   <el-header style="padding: 0; height: 60px; width: 100%">
      <div
         style="
            height: 100%;
            width: 100%;
            display: flex;
            justify-content: space-between;
         "
      >
         <!-- 控制侧边栏隐藏icon -->
         <div
            style="
               font-size: 25px;
               padding-top: 5px;
               margin-left: 16px;
               line-height: 60px;
               cursor: pointer;
            "
         >
            <el-icon
               v-show="asideShow"
               @click="store.commit('asideShow', false)"
               ><Fold
            /></el-icon>
            <el-icon
               v-show="!asideShow"
               @click="store.commit('asideShow', true)"
               ><Expand
            /></el-icon>
         </div>

         <!-- 用户个人信息下拉列表 -->
         <div style="padding-top: 4px; overflow: hidden; z-index: 99">
            <el-menu
               style="position: relative; border-bottom: none !important"
               active-text-color="#303133"
               class="el-menu-demo"
               mode="horizontal"
               :ellipsis="false"
            >
               <el-sub-menu index="none">
                  <template #title>
                     <div>
                        <el-icon style="margin-top: -2px; font-size: 20px">
                           <User />
                        </el-icon>
                        <span style="margin-right: 5px; font-size: 16px">{{
                           userInfo.name
                        }}</span>
                     </div>
                  </template>
                  <el-menu-item
                     @click="openPersonalInfoShowDialog()"
                     style="padding-left: 20px"
                     index="1"
                  >
                     <el-icon class="el_icon"><Document /></el-icon
                     >个人信息</el-menu-item
                  >
                  <el-menu-item
                     style="padding-left: 20px"
                     index="2"
                     @click="checkNowPassword()"
                  >
                     <el-icon class="el_icon"><Edit /></el-icon>
                     修改密码
                  </el-menu-item>
                  <el-menu-item
                     @click="logout()"
                     style="padding-left: 20px"
                     index="3"
                  >
                     <el-icon class="el_icon"><DArrowRight /></el-icon>登出
                  </el-menu-item>
               </el-sub-menu>
            </el-menu>
         </div>

         <!-- 个人信息弹窗 -->
         <el-dialog
            v-model="personalInfoDialogShow"
            :destroy-on-close="true"
            width="1060px"
         >
            <template #header>
               <h3 style="text-align: left">用户个人信息：</h3>
            </template>

            <div style="height: 100%; width: 100%">
               <!-- 用户基本信息 -->
               <el-row :gutter="10" type="flex" class="row-bg" justify="center">
                  <el-col :span="9">
                     <div>
                        <el-avatar
                           shape="square"
                           :size="150"
                           :src="require('@/assets/images/userImg_none.png')"
                           style="object-fit: fill"
                        ></el-avatar>
                     </div>
                  </el-col>

                  <el-col :span="1">
                     <el-divider
                        direction="vertical"
                        class="el-divider--vertical_userInfo"
                     ></el-divider>
                  </el-col>

                  <el-col :span="14">
                     <div style="margin-left: 50px; margin-top: -8px">
                        <el-descriptions
                           class="margin-top"
                           :column="1"
                           title="基本信息："
                        >
                           <template #extra>
                              <el-button
                                 type="primary"
                                 size="small"
                                 style="height: 30px"
                                 @click="personalInfoEditDialogShow = true"
                                 >编辑信息</el-button
                              >
                           </template>

                           <div>
                              <el-descriptions-item label="姓名:">{{
                                 userInfo.name
                              }}</el-descriptions-item>
                              <el-descriptions-item label="邮箱:">{{
                                 userInfo.email
                              }}</el-descriptions-item>
                              <el-descriptions-item label="学号/学工号:">{{
                                 userInfo.stuId
                              }}</el-descriptions-item>
                              <el-descriptions-item label="手机号:">{{
                                 userInfo.telephone
                              }}</el-descriptions-item>
                           </div>
                        </el-descriptions>
                     </div>
                  </el-col>
               </el-row>

               <el-divider content-position="left">当前担任角色：</el-divider>

               <!-- 角色列表 -->
               <!-- 角色多选框 -->
               <div style="margin-left: 50px; text-align: left">
                  <div>
                     <el-checkbox-group
                        style="margin-left: 30px"
                        v-model="userInfo.roles"
                     >
                        <el-checkbox
                           v-for="role of systemRoles"
                           :label="role"
                           :key="role"
                           disabled
                           style="margin-top: 10px; width: 200px"
                           >{{ role.roleName }}
                        </el-checkbox>
                     </el-checkbox-group>
                  </div>

                  <div style="margin: 15px 0"></div>
               </div>

               <el-divider content-position="left">当前可用权限：</el-divider>

               <!-- 权限列表 -->
               <!-- 权限多选框 -->
               <div style="margin-left: 50px; text-align: left">
                  <div>
                     <span>系统管理</span>

                     <div style="margin: 15px 0"></div>
                     <span style="margin-left: 15px">用户管理</span>
                     <el-checkbox-group
                        style="margin-left: 30px"
                        v-model="userInfo.permissions"
                     >
                        <el-checkbox
                           v-for="permission of systemPermissions.filter(
                              (permission) =>
                                 permission.permissionLevel ===
                                 '系统管理-用户管理'
                           )"
                           :label="permission"
                           :key="permission"
                           disabled
                           style="margin-top: 10px; width: 200px"
                           >{{ permission.permissionName }}
                        </el-checkbox>
                     </el-checkbox-group>

                     <div style="margin: 15px 0"></div>
                     <span style="margin-left: 15px">角色管理</span>
                     <el-checkbox-group
                        style="margin-left: 30px"
                        v-model="userInfo.permissions"
                     >
                        <el-checkbox
                           v-for="permission of systemPermissions.filter(
                              (permission) =>
                                 permission.permissionLevel ===
                                 '系统管理-角色管理'
                           )"
                           :label="permission"
                           :key="permission"
                           disabled
                           style="margin-top: 10px; width: 200px"
                           >{{ permission.permissionName }}
                        </el-checkbox>
                     </el-checkbox-group>

                     <div style="margin: 15px 0"></div>
                     <span style="margin-left: 15px">权限管理</span>
                     <el-checkbox-group
                        style="margin-left: 30px"
                        v-model="userInfo.permissions"
                     >
                        <el-checkbox
                           v-for="permission of systemPermissions.filter(
                              (permission) =>
                                 permission.permissionLevel ===
                                 '系统管理-权限管理'
                           )"
                           :label="permission"
                           :key="permission"
                           disabled
                           style="margin-top: 10px; width: 200px"
                           >{{ permission.permissionName }}
                        </el-checkbox>
                     </el-checkbox-group>

                     <div style="margin: 15px 0"></div>
                     <span style="margin-left: 15px">操作日志</span>

                     <el-checkbox-group
                        style="margin-left: 30px"
                        v-model="userInfo.permissions"
                     >
                        <el-checkbox
                           v-for="permission of systemPermissions.filter(
                              (permission) =>
                                 permission.permissionLevel ===
                                 '系统管理-操作日志'
                           )"
                           :label="permission"
                           :key="permission"
                           disabled
                           style="margin-top: 10px; width: 200px"
                           >{{ permission.permissionName }}
                        </el-checkbox>
                     </el-checkbox-group>
                  </div>

                  <div style="margin: 15px 0"></div>

                  <div>
                     <span>生源地图</span>
                     <el-checkbox-group
                        style="margin-left: 30px"
                        v-model="userInfo.permissions"
                     >
                        <el-checkbox
                           v-for="permission of systemPermissions.filter(
                              (permission) =>
                                 permission.permissionLevel === '生源地图'
                           )"
                           :label="permission"
                           :key="permission"
                           disabled
                           style="margin-top: 10px; width: 200px"
                           >{{ permission.permissionName }}
                        </el-checkbox>
                     </el-checkbox-group>
                  </div>

                  <div style="margin: 15px 0"></div>

                  <div>
                     <span>学生数据信息</span>
                     <el-checkbox-group
                        style="margin-left: 30px"
                        v-model="userInfo.permissions"
                     >
                        <el-checkbox
                           v-for="permission of systemPermissions.filter(
                              (permission) =>
                                 permission.permissionLevel === '学生数据信息'
                           )"
                           :label="permission"
                           :key="permission"
                           disabled
                           style="margin-top: 10px; width: 200px"
                           >{{ permission.permissionName }}
                        </el-checkbox>
                     </el-checkbox-group>
                  </div>

                  <div style="margin: 15px 0"></div>

                  <div>
                     <span>学院招生信息</span>
                     <el-checkbox-group
                        style="margin-left: 30px"
                        v-model="userInfo.permissions"
                     >
                        <el-checkbox
                           v-for="permission of systemPermissions.filter(
                              (permission) =>
                                 permission.permissionLevel === '学院招生信息'
                           )"
                           :label="permission"
                           :key="permission"
                           disabled
                           style="margin-top: 10px; width: 200px"
                           >{{ permission.permissionName }}
                        </el-checkbox>
                     </el-checkbox-group>
                  </div>

                  <div style="margin: 15px 0"></div>

                  <div>
                     <span>招生省份信息</span>
                     <el-checkbox-group
                        style="margin-left: 30px"
                        v-model="userInfo.permissions"
                     >
                        <el-checkbox
                           v-for="permission of systemPermissions.filter(
                              (permission) =>
                                 permission.permissionLevel === '招生省份信息'
                           )"
                           :label="permission"
                           :key="permission"
                           disabled
                           style="margin-top: 10px; width: 200px"
                           >{{ permission.permissionName }}
                        </el-checkbox>
                     </el-checkbox-group>
                  </div>
               </div>
            </div>
         </el-dialog>

         <!-- 个人信息编辑弹窗 -->
         <el-dialog v-model="personalInfoEditDialogShow" width="600px">
            <template #header>
               <h3 style="text-align: left">个人信息修改:</h3>
            </template>

            <el-form
               ref="editUserInfoDom"
               :model="userInfoEditForm"
               :rules="editUserInfoRules"
            >
               <el-form-item label="姓名" label-width="100" prop="name">
                  <el-input
                     v-model="userInfoEditForm.name"
                     style="width: 380px"
                     placeholder="请输入姓名："
                  ></el-input>
               </el-form-item>

               <el-form-item
                  label="联系电话"
                  label-width="100"
                  prop="telephone"
               >
                  <el-input
                     v-model="userInfoEditForm.telephone"
                     style="width: 380px"
                     placeholder="请输入联系电话："
                  ></el-input>
               </el-form-item>
            </el-form>

            <template #footer>
               <el-button @click="personalInfoEditDialogShow = false"
                  >取 消</el-button
               >
               <el-button type="primary" @click="editUserInfo()"
                  >修 改</el-button
               >
            </template>
         </el-dialog>

         <!-- 个人密码修改弹窗 -->
         <el-dialog v-model="personalChangePasswordDialogShow" width="600px">
            <template #header>
               <h3 style="text-align: left">密码修改:</h3>
            </template>

            <el-form
               ref="editPasswordDom"
               :model="userPasswordChangeForm"
               :rules="editPasswordRules"
            >
               <el-form-item
                  label="新密码"
                  label-width="100"
                  prop="newPassword"
               >
                  <el-input
                     v-model="userPasswordChangeForm.newPassword"
                     style="width: 380px"
                     show-password
                     placeholder="请输入密码："
                  ></el-input>
               </el-form-item>
               <el-form-item
                  label="确认密码"
                  label-width="100"
                  prop="reNewPassword"
               >
                  <el-input
                     v-model="userPasswordChangeForm.reNewPassword"
                     style="width: 380px"
                     show-password
                     placeholder="请再次输入密码："
                  ></el-input>
               </el-form-item>
            </el-form>

            <template #footer>
               <el-button @click="personalChangePasswordDialogShow = false"
                  >取 消</el-button
               >
               <el-button type="primary" @click="changePassword()"
                  >提 交</el-button
               >
            </template>
         </el-dialog>
      </div>
   </el-header>
</template>

<script>
import router from "@/rooter";
import $axios from "@/axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
import { reactive, computed, onMounted, ref } from "vue";

export default {
   name: "MainHeader",
   setup() {
      const store = useStore();

      // 系统所有角色
      let systemRoles = ref([]);
      // 系统所有权限
      let systemPermissions = ref([]);

      // 控制个人信息显示弹窗是否显示
      let personalInfoDialogShow = ref(false);

      // 用户基本信息
      let userInfo = reactive({
         id: "",
         stuId: "",
         name: "",
         email: "",
         telephone: "",
         roles: [],
         permissions: [],
      });

      // 控制侧边栏是否显示
      let asideShow = computed(() => {
         return store.state.asideShow;
      });

      // 用户登出
      function logout() {
         localStorage.removeItem("token");
         store.commit("currentLoginUser", {});
         router.replace("/login");
      }

      // 个人信息弹窗打开事件
      function openPersonalInfoShowDialog() {
         personalInfoDialogShow.value = true;

         // 获取系统所有角色
         $axios.get("/role/allRole").then((resp) => {
            systemRoles.value = resp.data.data;
            console.log(systemRoles.value);
         });

         // 获取系统所有权限
         $axios.get("/permission/allPermissions").then((resp) => {
            systemPermissions.value = resp.data.data;
            console.log(systemPermissions.value);
         });
      }

      //=====================

      // 控制个人信息编辑弹窗是否显示
      let personalInfoEditDialogShow = ref(false);

      // 个人信息编辑dom
      let editUserInfoDom = ref(null);

      // 个人信息修改表单
      let userInfoEditForm = reactive({
         id: "",
         name: "",
         telephone: "",
      });

      // 个人信息修改规则
      const editUserInfoRules = {
         name: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
         telephone: [
            { required: true, message: "请输入联系电话", trigger: "blur" },
            {
               validator: (rule, value, callback) => {
                  const reg = /^[1][3-9][0-9]{9}$/;
                  if (value == "" || value == undefined || value == null) {
                     callback();
                  } else {
                     if (!reg.test(value) && value != "") {
                        callback(new Error("请输入正确的电话号码"));
                     } else {
                        callback();
                     }
                  }
               },
               required: true,
               trigger: "blur",
            },
         ],
      };

      // 个人信息修改
      function editUserInfo() {
         editUserInfoDom.value.validate((valid) => {
            if (valid) {
               // 判断修改信息表单是否有改变
               if (
                  userInfoEditForm.name == userInfo.name &&
                  userInfoEditForm.telephone == userInfo.telephone
               ) {
                  ElMessage({
                     type: "warning",
                     message: "未更改任何内容",
                     duration: 1500,
                  });
                  return;
               }

               // 发送axios请求
               $axios
                  .put("/user/updateUserInfo", userInfoEditForm)
                  .then((resp) => {
                     ElMessage({
                        type: "success",
                        message: "修改成功",
                        duration: 1500,
                     });

                     setTimeout(() => {
                        window.location.reload();
                     }, 500);
                  });
            } else {
               ElMessage({
                  type: "error",
                  message: "请填写正确的信息",
                  duration: 1500,
               });
            }
         });
      }

      //=====================

      // 密码表单dom
      let editPasswordDom = ref(null);

      // 控制密码修改dialog是否显示
      let personalChangePasswordDialogShow = ref(false);

      // 用户密码修改表单
      let userPasswordChangeForm = reactive({
         id: "",
         newPassword: "",
         reNewPassword: "",
      });

      // 密码修改前，检查当前登录密码是否正确
      function checkNowPassword() {
         ElMessageBox.prompt("请输入当前密码", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
         }).then(({ value }) => {
            if (value) {
               let checkPasswordForm = {
                  id: userInfo.id,
                  password: value,
               };

               $axios
                  .post("/user/checkPassword", checkPasswordForm)
                  .then(() => {
                     ElMessage({
                        type: "success",
                        message: "密码验证成功，请修改密码",
                     });
                     personalChangePasswordDialogShow.value = true;
                  });
            }
         });
      }

      // 用户密码修改规则
      const editPasswordRules = {
         newPassword: [
            { required: true, message: "请输入密码", trigger: "blur" },
         ],
         reNewPassword: [
            { required: true, message: "请再次输入密码", trigger: "blur" },
            {
               validator: (rule, value, callback) => {
                  if (value === "") {
                     callback(new Error("请再次输入密码"));
                  } else if (value !== userPasswordChangeForm.newPassword) {
                     callback(new Error("两次输入密码不一致!"));
                  } else {
                     callback();
                  }
               },
               required: true,
               trigger: "blur",
            },
         ],
      };

      // 用户密码修改
      function changePassword() {
         editPasswordDom.value.validate((valid) => {
            if (valid) {
               let changePasswordForm = {
                  id: userInfo.id,
                  password: userPasswordChangeForm.newPassword,
               };

               $axios
                  .put("/user/updateUserPassword", changePasswordForm)
                  .then((resp) => {
                     ElMessage({
                        type: "success",
                        message: "密码修改成功，请重新登录",
                        duration: 1500,
                     });

                     setTimeout(() => {
                        logout();
                     }, 500);
                  });
            } else {
               ElMessage({
                  type: "error",
                  message: "请填写正确的信息",
                  duration: 1500,
               });
            }
         });
      }

      onMounted(async () => {
         
         // 获取当前登录用户的基本信息
         const currentLoginUserInfo = await $axios.get("/user/info");

         const currentLoginUser = currentLoginUserInfo.data.data;

         for (let item in userInfo) {
               userInfo[item] = currentLoginUser[item];
            }

            // 用户编辑表单的信息植入，用户可以打开编辑页面直接显示当前用户的信息
            for (let item in userInfoEditForm) {
               userInfoEditForm[item] = currentLoginUser[item];
            }

         store.commit("currentLoginUser", currentLoginUser);
      });

      return {
         store,
         asideShow,
         userInfo,
         logout,
         personalInfoDialogShow,
         openPersonalInfoShowDialog,
         systemRoles,
         systemPermissions,
         personalInfoEditDialogShow,
         userInfoEditForm,
         editUserInfo,
         editUserInfoRules,
         editUserInfoDom,
         personalChangePasswordDialogShow,
         editPasswordDom,
         userPasswordChangeForm,
         editPasswordRules,
         checkNowPassword,
         changePassword,
      };
   },
};
</script>

<style scoped>
.el_icon {
   font-size: 15px;
   color: #919398;
}

.el-divider--vertical {
   display: inline-block;
   width: 1px;
   height: 12em;
   margin: 0 8px;
   margin-top: -10px;
   vertical-align: middle;
   position: relative;
}
</style>

<style>
.el-descriptions__body {
   background-color: transparent;
}
.el-divider__text {
   background-color: #f7f9fa;
}

.el-menu--horizontal > .el-sub-menu.is-active .el-sub-menu__title {
   border-bottom: none;
}

.el-checkbox__input.is-checked + .el-checkbox__label {
   color: #409eff !important;
}
</style>

